<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { Search, ArrowRight, VideoPlay } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import Header from '../components/Header.vue'
import { getAllCourseClassify, getCoursePage, getCourseClassifyById } from '@/api/course'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 搜索关键词
const searchKeyword = ref('')

// 方向分类
const directions = ref([
  { id: 'all', name: '全部' },
  { id: 'ai', name: 'AI通识课程' },
  { id: 'programming', name: '程序设计语言' },
  { id: 'computer', name: '计算机基础' },
  { id: 'algorithm', name: '算法设计' }
])

// 子类分类映射
const subCategoriesMap = {
  all: [
    { id: 'all', name: '全部' }
  ],
  ai: [
    { id: 'all', name: '全部' },
    { id: 'ai-basic', name: 'AI通识基础课' },
    { id: 'ai-core', name: 'AI通识核心课' },
    { id: 'ai-case', name: 'AI通识案例课(AI+X)' }
  ],
  programming: [
    { id: 'all', name: '全部' },
    { id: 'python', name: 'Python程序设计' },
    { id: 'cpp', name: 'C/C++程序设计' },
    { id: 'java', name: 'Java程序设计' },
    { id: 'javascript', name: 'JavaScript程序设计' },
    { id: 'go', name: 'Go语言程序设计' }
  ],
  computer: [
    { id: 'all', name: '全部' },
    { id: 'basic', name: '计算机基础知识' },
    { id: 'architecture', name: '计算机体系结构' },
    { id: 'os', name: '操作系统' }
  ],
  algorithm: [
    { id: 'all', name: '全部' },
    { id: 'basic-algo', name: '基础算法' },
    { id: 'advanced-algo', name: '高级算法' },
    { id: 'ai-algo', name: 'AI算法' }
  ]
}

// 当前选中的分类
const activeDirection = ref('all')
const activeSubCategory = ref('all')
const activeTab = ref('latest') // latest or hot

// 当前显示的子类列表
const currentSubCategories = ref(subCategoriesMap.all)

// 监听方向变化，更新子类列表
watch(activeDirection, (newDirection) => {
  currentSubCategories.value = subCategoriesMap[newDirection] || subCategoriesMap.all
  activeSubCategory.value = 'all' // 重置子类选择
})

const courses = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

const selectedCategory = ref('')

// 新增：当前分类ID
const selectedCategoryId = ref('')

// 新增：根据分类ID加载课程
const loadCoursesByCategory = async (classifyId) => {
  if (!classifyId) {
    // 加载全部课程
    loadCourses()
    return
  }
  const res = await getCourseClassifyById(classifyId)
  if (res.code === 0 || res.code === 200) {
    courses.value = res.data.courses || []
    total.value = res.data.courseCount || 0
  }
}

const loadCourses = async () => {
  const params = {
    page: currentPage.value,
    pageSize: pageSize.value,
    courseName: searchKeyword.value
  }
  if (selectedCategory.value) {
    params.courseClassify = selectedCategory.value
  }
  // 可根据 activeTab.value === 'hot' 增加排序参数
  const res = await getCoursePage(params)
  if (res.code === 0 || res.code === 200) {
    courses.value = res.data.records || []
    total.value = res.data.total || 0
  }
}

onMounted(async () => {
  const res = await getAllCourseClassify()
  if (res.code === 0 || res.code === 200) {
    categoryList.value = res.data.records || []
  }
  loadCourses()
})

watch([selectedCategory, searchKeyword, activeTab], () => {
  currentPage.value = 1
  loadCourses()
})

const handlePageChange = (page) => {
  currentPage.value = page
  loadCourses()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCourses()
}

// 筛选后的课程列表
const filteredCourses = computed(() => {
  return courses.value.filter(course => {
    // 方向筛选
    if (activeDirection.value !== 'all' && course.direction !== activeDirection.value) {
      return false
    }
    // 子类筛选
    if (activeSubCategory.value !== 'all' && course.subCategory !== activeSubCategory.value) {
      return false
    }
    return true
  })
})

// 处理搜索
const handleSearch = () => {
  console.log('搜索关键词:', searchKeyword.value)
}

// 处理方向切换
const handleDirectionChange = (directionId) => {
  activeDirection.value = directionId
}

// 处理子类切换
const handleSubCategoryChange = (categoryId) => {
  activeSubCategory.value = categoryId
}

// 查看课程详情
const viewCourseDetail = (courseId) => {
  router.push(`/course/${courseId}`)
}

// 播放课程视频
const playCourseVideo = (course) => {
  router.push({
    name: 'video-player',
    params: {
      courseId: course.courseId,
      title: course.courseName,
      category: course.courseClassify,
      description: course.courseDescription
    }
  })
}

// 新建课程
const createCourse = () => {
  console.log('新建课程')
}

// 查看新手指引
const viewGuide = () => {
  console.log('查看新手指引')
}

const categoryList = ref([])

// 修改selectCategory，支持按分类ID查询
const selectCategory = (name, id) => {
  selectedCategory.value = name
  selectedCategoryId.value = id || ''
  if (id) {
    loadCoursesByCategory(id)
  } else {
    loadCourses()
  }
}

</script>

<template>
  <div class="learning-container">
    <Header />
    
    <!-- 课程头部 -->
    <div class="course-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="title">智慧课程</h1>
          <p class="description">集学习、实验、考试、AI教学于一体的课程资源</p>
        </div>
        <div class="header-right">
          <img src="https://picsum.photos/500/300" alt="课程插图">
        </div>
      </div>
    </div>
    
    <div class="course-content">
      <!-- 分类导航 -->
      <div class="category-nav">
        <span class="nav-label">类别：</span>
        <el-button
          :type="selectedCategory === '' ? 'primary' : 'default'"
          @click="selectCategory('', '')"
          size="small"
        >全部</el-button>
        <el-button
          v-for="item in categoryList"
          :key="item.classifyId"
          :type="selectedCategory === item.classifyName ? 'primary' : 'default'"
          @click="selectCategory(item.classifyName, item.classifyId)"
          size="small"
          class="category-button"
        >{{ item.classifyName }}</el-button>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <div class="filter-left">
          <el-radio-group v-model="activeTab">
            <el-radio-button label="latest">最新</el-radio-button>
            <el-radio-button label="hot">最热</el-radio-button>
          </el-radio-group>
        </div>
        <div class="filter-right">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入课程、姓名或学校名称进行搜索"
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <!-- 课程列表 -->
      <div class="course-list">
        <div class="course-grid">
          <div 
            v-for="course in courses" 
            :key="course.courseId" 
            class="course-card"
          >
            <div class="tech-card">
              <div class="cover-wrapper" @click="viewCourseDetail(course.courseId)">
                <img :src="course.courseCover || 'https://img.tech/cover-default.png'" class="cover-img" :alt="course.courseName" />
                <div class="course-tag" v-if="course.tag">{{ course.tag }}</div>
                <div class="course-hot" v-if="course.isHot">热门</div>
              </div>
              <div class="card-content">
                <h3 class="course-title-tech">{{ course.courseName }}</h3>
                <div class="course-category-tech">{{ course.courseClassify }}</div>
                <div class="course-desc-tech">{{ course.courseDescription || '暂无简介' }}</div>
                <div class="card-actions">
                  <el-button 
                    type="primary" 
                    class="play-button"
                    @click.stop="playCourseVideo(course)"
                    :disabled="!course.videoUrl"
                  >
                    <el-icon><VideoPlay /></el-icon>
                    播放视频
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="courses.length === 0" class="empty-state">
          <el-empty description="暂无课程" />
        </div>
        
        <el-pagination
          v-if="total > 0"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[12, 24, 48]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.learning-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
  font-family: 'Inter', 'Source Sans Pro', 'Microsoft YaHei', sans-serif;
}

.course-header {
  padding: 40px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 180px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(229, 231, 235, 0.7);
}

.header-left {
  flex: 1;
  padding-right: 40px;
}

.header-left .title {
  font-size: 28px;
  color: #2c5dff;
  margin: 0 0 12px;
  position: relative;
  font-weight: 700;
}

.header-left .description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
  line-height: 1.6;
}

.header-right {
  width: 320px;
  height: 180px;
  overflow: hidden;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
}

.header-right img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.course-content {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.category-nav {
  background: #fff;
  padding: 25px;
  border-radius: 16px;
  margin-bottom: 25px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.category-button {
  margin-bottom: 5px;
}

.nav-label {
  color: #6b7280;
  margin-right: 8px;
  font-weight: 500;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  background: #fff;
  border-radius: 16px;
  padding: 20px 25px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
}

.search-input {
  width: 300px;
}

.course-list {
  padding-bottom: 30px;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.course-card {
  width: 100%;
  height: 100%;
}

.empty-state {
  background: #fff;
  border-radius: 16px;
  padding: 50px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  border: 1px solid rgba(229, 231, 235, 0.7);
  text-align: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tech-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  border: 1px solid rgba(229, 231, 235, 0.7);
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tech-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 15px 35px rgba(44, 93, 255, 0.15);
  border-color: rgba(44, 93, 255, 0.3);
}

.cover-wrapper {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-bottom: 2px solid #f0f3ff;
}

.card-content {
  padding: 20px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.course-title-tech {
  color: #333;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-category-tech {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.course-category-tech::before {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  background: #2c5dff;
  border-radius: 50%;
  margin-right: 8px;
}

.course-desc-tech {
  color: #6b7280;
  font-size: 15px;
  min-height: 36px;
  margin-bottom: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  flex-grow: 1;
}

.course-tag {
  position: absolute;
  top: 10px;
  left: 10px;
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  color: white;
  padding: 5px 12px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 5px 15px rgba(44, 93, 255, 0.2);
}

.course-hot {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #f56c6c;
  color: white;
  padding: 5px 12px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 5px 15px rgba(245, 108, 108, 0.2);
}

.card-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.play-button {
  width: 100%;
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  border: none;
  color: white;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.play-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(44, 93, 255, 0.2);
}

.play-button:disabled {
  background: #94a3b8;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.play-button .el-icon {
  font-size: 16px;
}

:deep(.el-button--primary) {
  background-color: #2c5dff;
  border-color: #2c5dff;
}

:deep(.el-button--primary:hover), 
:deep(.el-button--primary:focus) {
  background-color: #1c4de0;
  border-color: #1c4de0;
}

:deep(.el-radio-button__orig-radio:checked+.el-radio-button__inner) {
  background-color: #2c5dff;
  border-color: #2c5dff;
  box-shadow: -1px 0 0 0 #2c5dff;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 25px;
  }
  
  .header-left {
    padding-right: 0;
    margin-bottom: 20px;
    text-align: center;
  }
  
  .header-right {
    width: 100%;
    height: 180px;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .filter-right, .search-input {
    width: 100%;
  }
  
  .course-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
}

@media (max-width: 576px) {
  .course-grid {
    grid-template-columns: 1fr;
  }
  
  .category-nav {
    padding: 15px;
  }
}
</style> 